package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/*
    Mapper工具类


 */
public class MapperUtils {

    private static SqlSessionFactory factory = null;

    private MapperUtils(){}
    //静态代码块
    static {
        // 1.读取核心配置文件信息
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("sqlMapper.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

//        2.构建SqlSessionFaction工厂对象
         factory = new SqlSessionFactoryBuilder().build(is);

    }

    public static SqlSession  getSqlSession(){

        return factory.openSession();
    }

    public static void close(SqlSession session){
        if (session!=null){
            session.commit();
            session.close();
        }

    }
}
